<script setup lang="ts">
import {object, string, type InferType} from 'yup'
import type {FormSubmitEvent} from '#ui/types'

const emit = defineEmits();

const regMobile = /^1[3-9]\d{9}$/
const regexPassword = /^(?=.*[a-zA-Z])(?=.*[\d!@#$%^&*(),.?":{}|<>])|(?=.*\d)(?=.*[a-zA-Z!@#$%^&*(),.?":{}|<>])|(?=.*[!@#$%^&*(),.?":{}|<>])(?=.*[a-zA-Z\d]).{6,30}$/;
import {ref as yupRef} from 'yup'

const schema = object({
  username: string()
      .matches(regMobile, '请输入正确的手机号码')
      .required('请输入手机号码'),
  password: string()
      .matches(regexPassword, '密码至少包含两种类型（字母、数字、特殊符号），长度6到30位')
      .required('请输入密码'),
  repeatPassword: string()
      .required('请输入重复密码')
      .oneOf([yupRef("password")], "重复密码和密码不一致"),
})

type Schema = InferType<typeof schema>

const state = reactive({
  username: undefined,
  password: undefined,
  repeatPassword: undefined,
})
const loading = ref(false)

import {useMessage} from 'naive-ui'

const message = useMessage()
const user = useUserStore()

const captchaFlag = ref(false)

const captchaSuccess = async (e: any) => {
  captchaFlag.value = false
  loading.value = true
  const {data, error} = await user.signUp({...state, ...e})


  if (error != null && error.value != null) {
    message.error(error.value.data.errMsg)
    loading.value = false
  } else {
    message.success(`注册成功，正在为您自动登录`)
    setTimeout(async () => {
      await user.signIn({...state, ...e})
      emit('success', data.value)
      loading.value = false
    }, 500)
  }
}


async function onSubmit(event: FormSubmitEvent<Schema>) {
  captchaFlag.value = true
  await captchaSuccess({})
}
</script>

<template>
  <div class="mx-auto w-full max-w-sm pb-6">
    <p class="text-2xl text-gray-900 dark:text-white font-bold text-center">创建账号</p>
  </div>
  <UForm :schema="schema" :state="state" class="space-y-4 w-full" @submit="onSubmit">
    <UFormGroup :label="`手机号`" name="username">
      <UInput v-model="state.username"/>
    </UFormGroup>

    <UFormGroup :label="`密码`" name="password">
      <UInput v-model="state.password" type="password"/>
    </UFormGroup>

    <UFormGroup :label="`重复密码`" name="repeatPassword">
      <UInput v-model="state.repeatPassword" type="password"/>
    </UFormGroup>
    <UButton :loading="loading" type="submit" block>
      注册
    </UButton>
  </UForm>
<!--  <Captcha :show="captchaFlag" @success="captchaSuccess"/>-->
</template>
